<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Bid_Goods extends Model
{
    // 竞拍商品表
    protected $table = "bid_goods";
    public $timestamps = false;
    protected $guarded = ['id'];

    protected static function booted()
    {
        static::retrieved(function ($bidGoods) {
            $now = Carbon::now();
            $start = Carbon::parse($bidGoods->start_time);
            $end = Carbon::parse($bidGoods->end_time);
            /*
             * 更新拍卖品状态
             * 0:未开拍||1:拍卖中||2:成交||3:流拍
             */

            if ($now->lessThan($start))
            // 未开始
                $bidGoods->update(['status' => 0, 'winner_id' => null,'max_price' => $bidGoods->init_price]);
            elseif ($now->greaterThan($start) && $now->lessThan($end))
            // 进行中
                $bidGoods->update(['status' => 1, 'winner_id' => null]);
            else
            // 已结束
            {
                if (!$bidGoods->bid->isEmpty()) { // 成交,更新赢取人id 并生成订单
                    $max = $bidGoods->bid->max('price');
                    $bidGoods->update(
                        [
                            'winner_id' => $bidGoods->bid->where('price', $max)->pop()->user->id,
                            'status' => 2,
                        ]
                    );

                    // 生成拍卖订单
                    Bid_Order::firstOrCreate([ // 通过id检索数据库
                        'item_id' => $bidGoods->id,
                        'buyer_id' => $bidGoods->winner_id,
                        'seller_id' => $bidGoods->craftsman_id,
                    ], [ // 没有则创建
                        'order_id' => Str::finish(rand(100000, 999999), rand(1000000, 9999999)), // 生成13位随机数字码
                        'order_time' => now(),
                    ]);

                } else { // 流拍
                    $bidGoods->update(['status' => 3]);
                }
            }
        });

        static::addGlobalScope('bidCount', function (Builder $builder) {
            $builder->withCount('bid');
        });
    }

    public function bid()
    {
        return $this->hasMany('App\Bid', 'bid_goods_id', 'id');
    }

    public function cate()
    {
        return $this->belongsTo('App\Category', 'cate_id');
    }

    public function craftsman()
    {
        return $this->belongsTo('App\Craftsman');
    }
}
